package com.example.demonstrate.wang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.demonstrate.wang.service.IWebSocketService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import javax.websocket.server.PathParam;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author along
 * @Date 2024/6/12 15:02
 * @Description webSocket服务支持
 */

@Service
public class WebSocketServerSupport implements IWebSocketService {

    /**
     * 日志
     */
    private final static Logger LOG = LoggerFactory.getLogger(WebSocketServerSupport.class);

    /**
     * 记录当前在线连接数
     */
    private static int onlineCount = 0;

    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static ConcurrentHashMap<String, WebSocketServerSupport> webSocketMap = new ConcurrentHashMap<>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;

    /**
     * 用户id
     */
    private String userId;

    /**
     * 连接建立成功调用的方法
     */
    @Override
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        this.userId = userId;
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            webSocketMap.put(userId, this);
        } else {
            webSocketMap.put(userId, this);
            addOnlineCount();
        }
        LOG.info("用户连接:" + userId + ",当前在线人数为:" + getOnlineCount());
        try {
            sendMessage("连接成功");
        } catch (Exception e) {
            LOG.error("用户:" + userId + ",网络异常!!!!!!");
        }
    }

    @Override
    public void onMessage(Session session, String message) {
        LOG.info("用户消息:" + userId + ",报文:" + message);
        try {
            //解析发送的报文
            JSONObject jsonObject = JSONObject.parseObject(message);
            //追加发送人(防止串改)
            jsonObject.put("fromUserId", this.userId);
            String toUserId = jsonObject.getString("toUserId");
            //传送给对应toUserId用户的websocket
            if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) {
                webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString());
            }
            else {
                LOG.error("请求的userId:" + toUserId + "不在该服务器上");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClose() {
        if (webSocketMap.containsKey(userId)) {
            webSocketMap.remove(userId);
            subOnlineCount();
        }
    }

    @Override
    public void onError(Session session, Throwable error) {
        LOG.error("用户错误:" + this.userId + ",原因:" + error.getMessage());
        error.printStackTrace();
    }

    /**
     * 发送自定义消息
     * @param message
     * @param userId
     * @throws Exception
     */
    public static void sendInfo(String message, @PathParam("userId") String userId) throws Exception {
        LOG.info("发送消息到:" + userId + "，报文:" + message);
        if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) {
            webSocketMap.get(userId).sendMessage(message);
        }
        else {
            LOG.error("用户:" + userId + "不在线！");
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebSocketServerSupport.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        WebSocketServerSupport.onlineCount--;
    }

    /**
     * 发送消息
     * @param message
     * @throws Exception
     */
    public void sendMessage(String message) throws Exception{
        this.session.getBasicRemote().sendText(message);
    }
}
